import Vue from 'vue';
import Vuex from 'vuex';
import config from '@/config/app';

Vue.use(Vuex)

let lifeData = {};
try {
  // 尝试获取本地是否存在lifeData变量，第一次启动APP时是不存在的
  lifeData = uni.getStorageSync(config.projectKey);
  console.log(config.projectKey, lifeData.userInfo, uni.getStorageSync('DNCache'));
} catch (e) {}

// 需要永久存储，且下次APP启动需要取出的，在state中的变量名
let saveStateKeys = ['userInfo', 'userToken', 'temToken', 'appConfig', 'isLogin'];

// 保存变量到本地存储中
const saveLifeData = function(key, value) {
  if (saveStateKeys.indexOf(key) != -1) {
    let tmp = uni.getStorageSync(config.projectKey);
    tmp = tmp ? tmp : {};
    tmp[key] = value;
    uni.setStorageSync(config.projectKey, tmp);
  }
}
const store = new Vuex.Store({
  state: {
    userInfo: {},
    userToken: lifeData.userToken || null,
    temToken: null,
    isLogin: lifeData.userToken || false
  },
  mutations: {
    $uStore(state, payload) {
      let nameArr = payload.name.split('.');
      let saveKey = '';
      let len = nameArr.length;
      if (nameArr.length >= 2) {
        let obj = state[nameArr[0]];
        for (let i = 1; i < len - 1; i++) {
          obj = obj[nameArr[i]];
        }
        obj[nameArr[len - 1]] = payload.value;
        saveKey = nameArr[0];
      } else {
        state[payload.name] = payload.value;
        saveKey = payload.name;
      }
      // 保存变量到本地
      saveLifeData(saveKey, state[saveKey])
    },

    // 退出曾路
    logout(state) {
      state.isLogin = false;
      console.log('logout');
      state.userToken = null;
      saveLifeData('userToken', null);
      state.userInfo = false;
      saveLifeData('userInfo', null);
      uni.reLaunch({
        url: '/pages/index/index'
      });
    },
    login(state, payload) {
      state.userToken = payload.token;
      saveLifeData('userToken', payload.token);
    },
    updatePushInfo(state, payload) {
      state.vxPushInfo = payload;
      saveLifeData('vxPushInfo', state.vxPushInfo);
      this.dispatch('updatePushClient');
    },
    saveConfig(state, payload) {
      state.config = payload
    },
		setUser(state, data) {
			state.userInfo = data
		},

  },
  actions: {
    getImageUrl({
      commit,
      state
    }, url) {
      return url ? `${this.config.domain}${url}` : ''
    },
    async getConfig({
      commit,
      state
    }) {
      const data = await uni.$u.api.getConfig()
      commit('saveConfig', data)
    },
    async getUser({
      commit,
      state
    }) {
      const data = await getUserCenter({
        token: state.token || state.temToken
      })
      commit('setUser', data)
      // this.userInfo = data
    },
    login(token) {
      this.token = token
      cache.set(TOKEN_KEY, token)
    },
    logout() {
      this.token = ''
      this.userInfo = {}
      cache.remove(TOKEN_KEY)
    },
    // 向服务端更新用户推送信息
    async updatePushClient({
      state
    }) {
      if (state.userToken && state.vxPushInfo) {
        try {
          // 请求接口保存vxPushInfo
        } catch (e) {
          console.log(e);
        }
      }
    },
  },
  getters: {

  }
})

export default store;